package com.atguigu.gmall.payment.receiver;

import com.atguigu.gmall.common.constant.RabbitConst;
import com.atguigu.gmall.payment.service.api.PaymentService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author: 封捷
 * @create-date: 2022/9/17 11:12
 */
@Component
public class PaymentInfoReceiver {

    @Autowired
    private PaymentService paymentService;

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = RabbitConst.EXCHANGE_DIRECT_PAYMENT_CLOSE),
            value = @Queue(value = RabbitConst.QUEUE_PAYMENT_CLOSE),
            key = {RabbitConst.ROUTING_PAYMENT_CLOSE}
    ))
    public void closePaymentInfo(Long orderId, Message message, Channel channel) throws IOException {
        try {
            // 核心操作：执行 PaymentInfo 的关闭
            paymentService.closePaymentInfo(orderId);

            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();

            Boolean redelivered = message.getMessageProperties().getRedelivered();

            if (redelivered) {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        }
    }

}
